<template>
  <div class="v-header">
    <!--  头部-->
    <div  v-show="isElectron" class="_window-bar" :style="{height:$globalConfig.windowBarHeight}">
      <div class="g-m-t-4 g-m-l-4">
        <img src="statics/images/mainpage/toplogo.svg" />
      </div>
      <span class="_text">试用版</span>
      <div class="g-flex-1">
      </div>
      <div class="_window-right-btns">
        <div class="_window-btn _min-btn" @click="windowClick('min')">
          <img src="statics/images/mainpage/wminimize.svg" />
        </div>
        <div class="_window-btn _max-btn" @click="windowClick('max')">
          <img ref="maxImg" :src="windowSize==='max'?'statics/images/mainpage/wmaximization2.svg':'statics/images/mainpage/wmaximization.svg'" />
        </div>
        <div class="_window-btn _close-btn" @click="windowClick('close')">
          <img src="statics/images/mainpage/wclose.svg" />
        </div>
      </div>

    </div>
    <div class="_header-content" :style="{height:$globalConfig.topBarHeight}">
      <div class="_col-left">
        <div class="_system-bar">
          <img
            src="statics/images/mainpage/topiconline.svg"
            class="topiconline"
          />
          <template v-for="(menu, index) in systemMenus">
            <a-dropdown
              :key="index"
              :visible="curShowMenu === menu.value"
              :trigger="['click']"
              :style="{
                textAlign: 'left',
                marginLeft: '10px',
                marginRight:'10px'
              }"
              overlayClassName="dropdown_border_custom"
              :disabled="menu.disabled"
            >
              <span class="_system-btn" :class="{_disabled: menu.disabled}" @click.stop="!menu.disabled && (curShowMenu = menu.value)">
                {{ menu.label }}
              </span>
              <m-menu
                slot="overlay"
                :menu="menu.subItems"
                size="small"
                @click-menu-item="handleMenuClick"
              >
              </m-menu>
            </a-dropdown>
          </template>
        </div>
        <div class="_tool-bar">
          <div style="min-width: 850px; display: flex; align-items: center">
            <img
              src="statics/images/mainpage/topiconline.svg"
              class="topiconline"
            />
            <span class="_tool-btn"   title="主页" @click="handleLinkToHome">
              <img
                src="statics/icons/app/topiconhome.svg"
                alt="主页"
              />
            </span>
            <span class="_tool-btn" title="新建" @click="newProject">
              <img
                src="statics/icons/app/topiconnew.svg"
                alt="新建"
              />
            </span>
            <span class="_tool-btn" title="打开" @click="openProject">
              <img
                src="statics/icons/app/topiconopen.svg"
                alt="打开"
              />
            </span>
            <span class="_tool-btn" :class="{_disabled:!hasCurProject}" title="关闭" @click="closeCurProject">
              <img
                src="statics/icons/app/topiconclose.svg"
                alt="关闭"
              />
            </span>

            <span class="_tool-btn" :class="{_disabled:!hasCurProject}" title="保存" @click="saveProject">
              <img
                src="statics/icons/app/topiconsave.svg"
                alt="保存"
              />
            </span>
            <span class="_tool-btn" :class="{_disabled:true}" title="上传" @click="onsc">
              <img
                src="statics/icons/app/topiconsc.svg"
                alt="上传"
              />
            </span>
            <span class="_tool-btn _disabled" title="打印" @click="print">
              <img
                src="statics/icons/app/topiconprint.svg"
                alt="打印"
              />
            </span>
            <span class="_tool-btn _disabled" title="搜索" @click="search">
              <img
                src="statics/icons/app/topiconsearch.svg"
                alt="搜索"
              />
            </span>

            <img
              src="statics/images/mainpage/topiconline.svg"
              class="topiconline"
              style="marginLeft:8px;marginRight:8px"
            />
            <span class="_tool-btn" :class="{_disabled:!hasCurProject}" style="padding-right: 8px" @click="openAddDiagramModal">
              <img
                src="statics/icons/app/topicontb.svg"
                alt="新建图表"
                style="marginRight:4px"
              />
              <span>新建图表</span>
            </span>
            <img
              src="statics/images/mainpage/topiconline.svg"
              style="marginLeft:8px"
              class="topiconline"
            />
            <a-dropdown :trigger="['click']" :disabled="!hasCurProject" @click="e => handleSimulation(e)">
              <span class="_tool-btn" :class="{_disabled:!hasCurProject}" style="width: 80px">
                <img
                  src="statics/icons/app/topiconsimulation.svg"
                  alt="仿真"
                  width="16px"
                  style="marginRight:4px"
                />
                <span>仿真</span>
                <a-icon type="down" style="font-size: 8px; margin-left: 6px"/>
              </span>
              <a-menu slot="overlay">
                <a-menu-item v-if="simulationList.length === 0">暂无数据</a-menu-item>
                <a-menu-item v-for="item in simulationList" :key="item.id">
                  {{ item.simulationName }}
                </a-menu-item>
              </a-menu>
            </a-dropdown>
            <img
              src="statics/images/mainpage/topiconline.svg"
              style="marginLeft:8px"
              class="topiconline"
            />
            <template v-if="$globalConfig.dodafPath">
              <span class="_tool-btn g-pd-l-5 g-pd-r-10" @click="handleOpenDodaf">
                <img
                  src="statics/images/mainpage/topdodaf.svg"
                  style="margin-right:2px;margin-left:2px"
              
                />
                dodaf
              </span>

              <img
                src="statics/images/mainpage/topiconline.svg"
                style="marginLeft:16px"
                class="topiconline"
              />

            </template>
        
            <!-- <span class="_tool-btn" :class="{_disabled:!hasCurProject}">
                <img
                  src="statics/images/mainpage/topiconpr.svg"
                  alt="在线"
                />
              </span> -->
            <a-select
              :value="curProjectId"
              style="margin-left:4px;font-size:12px;"
              class="_select"
              size="small"
              placeholder="暂无项目"
              notFoundContent="暂无项目"
              @change="handleCurProjectChange"
            >
              <a-select-option v-for="item in openedProjectList" :key="item.id" class="hasImage" :title="item.projectName">
                <img :src="item.icon">
                <span>{{ item.projectName }}</span>
              </a-select-option>
            </a-select>
            <img
              src="statics/images/mainpage/topiconline.svg"
              style="marginLeft:8px"
              class="topiconline"
            />
            <a-dropdown :trigger="['click']" :placement="placement">
              <span class="_tool-btn" :class="{_disabled: disabledLogin }" style="padding: 0 5px; min-width: 90px" @click.prevent="() => { !$globalConfig.user  &&  handleLogin()}">
                <img
                  src="statics/icons/app/picuser2.svg"
                  alt="登录"
                  width="16px"
                  style="margin: 0 4px 3px 0; vertical-align: middle;"
                />
                <span>{{($globalConfig.user && $globalConfig.user.userName) ? `${username}` : '协同登录'}}</span>
              </span>
              <a-menu v-show="$globalConfig.user" slot="overlay" :trigger="['click']">
                <a-menu-item key="0" @click="handleLogin">
                  <div class="image-box"><img src="statics/icons/app/topiconexchangeaccount.svg" alt=""></div>
                  切换账号
                </a-menu-item>
                <a-menu-item key="1" @click="logout">
                  <div class="image-box"><img src="statics/icons/app/topiconlogout.svg" alt=""></div>
                  退出
                </a-menu-item>
              </a-menu>
            </a-dropdown>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Menu from "src/components/common/ContextMenu/Menu";
import { confirmClose } from "src/components/common/ConfirmClose";
import {
  getUniqueName,
  storage,
  treeForEach,
  handleExcelData,
  handleReqifData,
  handleRenameTableName
} from "src/util/common";
import { MofModelRepositoryHelper, SysMLUtilHelper } from "src/api/sysml-imports";
import { addProject } from "../components/Home/modals/AddProject";
//// import TraceGrid from '../components/Matrix/TraceGrid';
//// import TraceGrid from '../components/Matrix/TraceGrid';
//// import { elementMatrix } from './common/ElementMatrix';
import localFile from "src/util/localFile/index";
import XLSX from "xlsx";
//// import XmlToJson from "src/util/XmlToJson";
import { GenericTableApi } from "src/api/shape/GenericTableApi";
import { graphHelper } from "src/api/GraphHelper";

import { parseDataToReqif } from 'src/util/reqifUtil';
//// import  iconRightMaxS from 'statics/images/mainpage/wmaximization.svg';
//// import  iconRightMaxL from 'statics/images/mainpage/wmaximization2.svg';
import { matlabSetting } from "src/components/Project/modals/MatlabSetting";
import { backupSetting } from "src/components/Project/modals/BackupSetting";
import { restoreBackup } from "src/components/Project/modals/RestoreBackup";
import { logSetting } from "src/components/Project/modals/LogSetting";
import { remoteProjectListModal } from "./cooperation/remoteProjectList";
import { saveProjectModal } from "./cooperation/saveProject";
import { publishRemoteProjectModal } from "./cooperation/publishRemoteProject";
import { updateReqModal } from "./cooperation/updateReqModal";
import { setReqSyncModal } from "./projectReq/setReqSync/modals/setReqSync";
import { submitUpdateModal } from "./cooperation/submitUpdate/submitUpdateModal";
import submitUpdate from "./cooperation/submitUpdate/submitUpdate.ts";
import updateModel from "./cooperation/submitUpdate/UpdateModel.ts";
import { loginModal } from "./login/login";
import { activeLicenseModal } from "./Help/license/license.vue";
import { aboutModal } from "./Help/About";

import { remoteAxios } from 'src/util/http';
import { actions } from 'src/pages/mxgraph/Actions';
import globalConfig from 'src/util/Global';
import { API } from '@/constants/api';
import graphNodeStatusFresher from 'src/components/cooperation/GraphNodeStatusFresher';
import { GraphNodeStatus } from 'src/constants/Enums.ts';
import { dodafSetting } from './Project/modals/DodafSetting.vue';
import { LocalFileService } from '@/util/localFile/LocalFileService';
import { VersionType } from '@/constants/Enums';
import { tipError, errorCode } from 'src/constants/ErrorConfig';

export default {
  name: "m-header",
  components: {
    "m-menu": Menu,
  },
  data() {
    return {
      curShowMenu: "", //// 当前显示的menu
      curSimulationId: undefined,
      simulationList: [
        //// { id: 1, simulationName: '大飞机模拟仿真' }
      ],
      windowSize: "mid", //// mid / max
      //// 登出显示
      logoutDropdown: false,
      placement: 'bottomLeft',
      token: !!storage.get('token'),
      username: this.$globalConfig.user ? this.$globalConfig.user.userName || '' : '',
      usernameA: (this.$globalConfig.user && this.$globalConfig.user.userName) ? this.$globalConfig.user.userName.substr(0, 1) : '',
      dropdownVisible: false,
      isDevMode: false
    };
  },
  computed: {
    isAppActive(){
      return app.$globalConfig.isAppActive;
    },
    disabledLogin(){
      return !this.isAppActive || !(app.$globalConfig.appVersionType === VersionType.ENTERPRICE); 
    },
    curProjectId() {
      return app.activeProjectId;
    },
    isElectron() {
      return this.$globalConfig.isElectron;
    },
    openedProjectList() {
      return Object.values(app.proxy.projects.map).map((i) => ({
        id: i.config.id,
        projectName: i.config.projectName,
        icon: i.config.online ? 'statics/icons/app/topiconcopr.svg' : 'statics/icons/app/topiconpr.svg',
      }));
    },
    hasCurProject() {
      return !!this.curProjectId;
    },

    fileMenu() {
      const disableImport = !(app.sysmlModel && !app.sysmlModel.disabled);
      return {
        label: "文件(F)",
        value: "file",
        disabled: !this.isAppActive,
        //// 文件
        subItems: [
          {
            label: "新建",
            value: "newProject",
            icon: "statics/icons/app/topiconnew.svg",
            showIcon: true,
          },
          {
            label: "打开",
            value: "openProject",
            icon: "statics/icons/app/topiconopen.svg",
            showIcon: true,
            isHR: true,
          },
          {
            label: "保存",
            value: "saveProject",
            disabled: !this.hasCurProject,
            icon: "statics/icons/app/topiconsave.svg",
            showIcon: true,
          },
          {
            label: "另存为",
            value: "saveAs",
            disabled: !this.hasCurProject,
            icon: "statics/icons/app/topiconSaveas.svg",
            showIcon: true,
          },
          {
            label: "关闭",
            value: "closeCurProject",
            disabled: !this.hasCurProject,
            icon: "statics/icons/app/topiconclose.svg",
            showIcon: true,
          },
          {
            label: "全部关闭",
            value: "closeAllProject",
            disabled: !this.hasCurProject,
            isHR: true,
            icon: "statics/icons/app/topiconcloseall2.svg",
            showIcon: true,
          },
          {
            label: "文件恢复",
            value: "restoreBackup",
            showIcon: true,
            disabled: !(this.$globalConfig.isElectron && app.activeProject),
            icon: "statics/icons/app/topiconrecovery.svg",
          },
          {
            label: "导入",
            //// disabled: true,
            disabled: disableImport,
            value: "",
            icon: "statics/icons/app/topiconleadin.svg",
            showIcon: true,
            clickDisabled: true,
            children: [
              {
                label: "导入项目",
                clickDisabled: true,
                disabled: app.activeProject && app.activeProject.config.online, //// 协同项目不支持导入项目
                children: [
                  {
                    label: "*.md3",
                    value: "importProject",
                  },
                  {
                    label: "*.xml",
                    value: "importProjectXML",
                  }
                ],
              },
              {
                label: "导入扩展包",
                clickDisabled: true,
                disabled: app.activeProject && app.activeProject.config.online, //// 协同项目不支持导入项目
                children: [
                  {
                    label: "*.md3p",
                    value: "importProfile",
                  }
                ],
              },
              {
                label: "导入需求表",
                clickDisabled: true,
                children: [
                  {
                    label: "Excel",
                    value: "importRequirementTableExcel",
                  },
                  {
                    label: "ReqIF",
                    value: "importRequirementTableReqif",
                  }
                ],
              }
            ],
          },
          {
            label: "导出",
            value: "export",
            clickDisabled: true,
            disabled: !this.hasCurProject,
            icon: "statics/icons/app/topiconexport.svg",
            showIcon: true,
            children: [
              {
                label: "导出项目",
                clickDisabled: true,
                children: [
                  { label: "*.md3", value: 'exportProject' },
                  { label: "*.xml", value: 'exportProjectXML' }
                ],
              }
              //// {
              ////   label: "导出构造包",
              ////   value: "exportReadOnlyProject",
              ////   children: [{ label: "*.md3p" }],
              //// },
              //// {
              ////   label: "导出需求表",
              ////   children: [
              ////     { label: "Excel" },
              ////     { label: "ReqlF" }
              ////   ],
              ////   ////  disabled: true
              //// }
            ],
          },
          {
            label: "打印",
            icon: "statics/icons/app/topiconprint.svg",
            showIcon: true,
          }
        ],
      };
    },
    //// 图表
    diagramMenu() {
      const allDi = graphHelper.getProjectAllDiagrams(
        app.activeProjectId
      );
      const recentDi =
        app.ui &&
        app.ui.recentDiagramIds
          .map((id) => {
            const diagramNode = allDi?.get(id);
            if (!diagramNode) return;
            return {
              label: diagramNode.title,
              value: "openDiagram",
              id: diagramNode.id,
              //// model: model,
            };
          })
          .filter(Boolean);
      return {
        label: "图表(D)",
        value: "diagram",
        disabled: !this.isAppActive || !this.hasCurProject,
        subItems: [
          {
            label: "创建图表",
            value: "openAddDiagramModal",
            showIcon: true,
          },
          {
            label: "最近的图表",
            children: recentDi,
            showIcon: true,
            disabled: !(recentDi && recentDi.length > 0),
          },
          {
            label: "打开全部图表",
            value: "openAllDiagrams",
            showIcon: true,
          }
        ],
      };
    },
    //// 分析
    analysisMenu() {
      return {
        label: "分析(A)",
        value: "analysis",
        disabled: !this.isAppActive,
        subItems: [],
      };
    },
    //// 用户
    usersMenu() {
      return {
        label: "用户(U)",
        value: "user",
        disabled: !this.isAppActive,
        subItems: [],
      };
    },
    //// 设置
    settingsMenu() {
      return {
        label: "设置(S)",
        value: "settings",
        disabled: !this.isAppActive,
        subItems: [
          {
            label: "插件设置",
            value: "plugSettings",
            showIcon: true,
            icon: "statics/icons/app/iconMatlab.svg",
            children: [
              {
                label: "Matlab",
                value: "showMatlabSetting",
              }
              //// {
              ////   label: "Dodaf",
              ////   value: "showDodafSetting",
              //// }
            ],
          },
          {
            label: "需求同步",
            value: "reqSync",
            showIcon: true,
            icon: "statics/icons/app/topiconxqtb.svg",
          },
          {
            label: "保存设置",
            value: "backupSettings",
            showIcon: true,
            disabled: !this.$globalConfig.isElectron,
            icon: "statics/icons/app/topiconbackupsettings.svg",
          },
          {
            label: "日志设置",
            value: "logSettings",
            showIcon: true,
            disabled: !this.$globalConfig.isElectron,
            icon: "statics/icons/app/topiconlogsettings.svg",
          }
        ],
      };
    },
    //// 协同
    cooperationMenu() {
      return {
        label: "协同(T)",
        value: "cooperation",
        //// TODO 根据登陆情况确定是否启用
        disabled: !this.isAppActive || false,
        subItems: [
          {
            label: "项目列表",
            value: "remoteProjectList",
            showIcon: true,
            disabled: !this.token,
            icon: "statics/icons/app/topiconxmlb.svg",
            isHR: true,
          },
          {
            label: "上传新项目",
            value: "publishRemoteProject",
            showIcon: true,
            disabled: !(app.activeProject && !app.activeProject.config.online && this.token),
            icon: "statics/icons/app/topiconksfbxxm.svg",
          },
          {
            label: "快速更新",
            value: "updateLocalProject",
            showIcon: true,
            disabled: !(app.activeProject && app.activeProject.config.online && this.token),
            icon: "statics/icons/app/topiconksgx.svg",
          },
          {
            label: "提交更改",
            value: "pushToRemoteProject",
            showIcon: true,
            disabled: !(app.activeProject && app.activeProject.config.online && this.token),
            icon: "statics/icons/app/topicontjgg.svg",
          },
          {
            label: "自动更新",
            value: "autoUpdate",
            showIcon: true,
            disabled: false,
            icon: "statics/icons/app/topiconzdgx.svg",
            children: [
              { label: "打开", value: "open" },
              { label: "关闭", value: "close" }
            ],
          },
          {
            label: "更新需求",
            value: "updateReq",
            showIcon: true,
            disabled: !(app.activeProject && this.token),
            icon: "statics/icons/app/topiconupdate.svg",
          }
        ],
      };
    },
    //// 帮助
    helpMenu() {
      return {
        label: "帮助(H)",
        value: "help",
        disabled: false,
        subItems: [
          {
            label: "使用手册",
            value: "helpqa",
            icon: "statics/icons/app/iconqa.svg",
            showIcon: true,
          },
          {
            label: "激活",
            value: "activeLicense",
            icon: "statics/icons/app/iconactivation.svg",
            showIcon: true,
          },
          {
            label: "关于",
            value: "about",
            icon: "statics/icons/app/iconabout.svg",
            showIcon: true,
          }
        ],
      };
    },
    systemMenus() {
      return [
        this.fileMenu,
        this.diagramMenu,
        this.analysisMenu,
        this.usersMenu,
        this.settingsMenu,
        this.cooperationMenu,
        this.helpMenu
      ];
    },
  },

  mounted() {
    window.addEventListener("click", this.handleWindowClick); //// 关闭下拉
  },
  beforeDestroy() {
    window.removeEventListener("click", this.handleWindowClick);
  },
  methods: {
    handleMenuClick(menuItem) {
      if (menuItem.clickDisabled) return;
      if (menuItem.disabled) return;
      this.curShowMenu = "";
      if (this[menuItem.value]) {
        this[menuItem.value](menuItem);
      } else {
        this.$messageBox.warn({
          text: '暂未提供此功能',
          key: '试用版',
          duration: 10
        });
      }
      //// this[menuItem.value] && this[menuItem.value](menuItem);
    },
    openDiagram(data) {
      this.$bus.emit("diagram-open", { id: data.id });
      //// treeUtil.openDiagram(data.model);
    },
    windowClick(eventType) {
      console.log('window click', eventType);
      if (!this.$globalConfig.isElectron) return;
      const win = window.$ele.electron.remote.BrowserWindow.getFocusedWindow();
      if (eventType === "min") {
        win.minimize();
      } else if (eventType === "max") {
        if (win.isMaximized()) {
          win.unmaximize();
          this.windowSize = "mid";
        } else {
          win.maximize();
          this.windowSize = "max";
        }
      } else if (eventType === "close") {
        this.handleCloseWindow(win);

      } else {
        console.log("未知事件", eventType);
      }
    },
    async handleCloseWindow(win) {
      const projectArr = Object.values(proxy.projects.map);
      if (app.activeProject) {
        const index = projectArr.findIndex(
          (project) => project.config.id === app.activeProjectId
        );
        projectArr.splice(index, 1);
        projectArr.push(app.activeProject);
      }
      projectArr.reverse();
      for (let i = 0; i < projectArr.length; i++) {
        const result = await this.closeProject(projectArr[i].config.id);
        if (result === "canceled") return;
      }
      win.close();
      app.server && app.server.close();
      //// proxy.projects.map
    },

    async closeProject(projectId) {
      const project = proxy.projects.get(projectId);
      const activeProjectId = app.activeProjectId;
      if (project.ui.modified) {
        const { type } = await confirmClose.popup({
          title: "保存",
          subTitle: "保存",
          content: `是否保存对${project.config.projectName}项目的更改？`,
          cancelText: "取消",
          cancelSave: "不保存",
          okText: "立即保存",
          status: "warn",
        });
        if (type === "cancel") return "canceled";
        else if (type === "save") {
          await localFile.saveProject(project);
          this.deleteProject(projectId);
        } else if (type === "unSave") {
          this.deleteProject(projectId);
        }
      } else {
        this.deleteProject(projectId);
      }
      if (activeProjectId === project.config.id) {
        const keys = Object.keys(proxy.projects.map);
        const lastKey = keys[keys.length - 1];
        proxy.activeProjectId = lastKey;
        this.$bus.emit("project-switch", { id: lastKey });
        if (!proxy.activeProjectId) {
          this.handleLinkToHome();
        }
      }
    },

    deleteProject(projectId) {
      const project = proxy.projects.get(projectId);
      LocalFileService.removeProject(project);

    },

    async closeCurProject() {
      if (!this.hasCurProject) {
        return;
      }
      await this.closeProject(app.activeProject.config.id);
    },
    async closeAllProject() {
      const projectArr = Object.values(proxy.projects.map);
      projectArr.forEach(async (item) => {
        await this.closeProject(item.config.id);
      });
    },

    handleLinkToHome() {
      if (this.$route.path !== "/home") this.$router.push("/home");
      app.proxy.activeProjectId = undefined;
    },
    newProject() {
      if (!this.isAppActive){
        app.$Confirm.popup({
          title: '项目未激活',
          content: '项目未激活',
          cancelText: '',
          status: 'warn'
        });
        return;
      }
      addProject
        .popup()
        .then((res) => {
          if (this.$route.path !== "/edit/default")
            this.$router.push("/edit/default");
        })
        .catch((e) => {
          e && console.error(e);
        });
      //// TraceGrid
    },
    saveAs() {
      localFile.saveAsProject(app.activeProject);
    },
    saveProject() {
      if (!this.hasCurProject) {
        return;
      }
      return localFile.saveProject(app.activeProject);
    },

    openProject() {
      if (!this.isAppActive){
        app.$Confirm.popup({
          title: '项目未激活',
          content: '项目未激活',
          cancelText: '',
          status: 'warn'
        });
        return;
      }
      localFile.openProject().then((project) => {
        localFile.switchToProject(project);
      }).catch(e => {
        console.log(e);
        if (e && e.cancel){
          console.log('canceled');
        } else {
          throw e;
        }
      });
    },
    importProject() {
      actions.getAction('importProjectMd3').onTreeMenuClick(app.sysmlModel);
    },
    importProjectXML() {
      actions.getAction('importProjectXML').onTreeMenuClick(app.sysmlModel);
    },
    async importRequirementTableExcel() {
      localFile.openExcel('excel')
        .then(res => {
          //// console.log('res', res);
          const name = res.name.split('.')[0];
          const requirements = handleExcelData(res);
          const packageNode = app.sysmlModel.importExcel(
            requirements
          );
          app.$bus.emit('project-modified');
          handleRenameTableName(packageNode, name);
        })
        .catch(err => console.log(err));
    },

    async importRequirementTableReqif() {
      localFile.openReqif('reqif')
        .then(res => {
          //// console.log('res', res);
          const name = res.name.split('.')[0];
          const requirements = handleReqifData(res);
          console.log('requirements', requirements);
          const packageNode = app.sysmlModel.importReqIf(
            requirements
          );
          app.$bus.emit('project-modified');
          handleRenameTableName(packageNode, name);
        })
        .catch(err => console.log(err));
    },

    importProfile() {
      //// debugger;
      const action = actions.getAction('importMd3p');
      if (!action) return;
      //// TODO
      action.onTreeMenuClick();

    },
    addToTable(req, diagram) {
      GenericTableApi.addRowShape({ diagram, modelElement: req });
      let elements = req
        .getOwnedMembers()
        .toArray()
        .filter((item) => SysMLUtilHelper.isRequirement(item));
      if (elements && elements.length > 0) {
        elements.forEach((item) => this.addToTable(item, diagram));
      }
    },
    exportReadOnlyProject() {
      localFile.saveAsProject(app.activeProject, false);
    },
    handleCurProjectChange(id) {
      proxy.activeProjectId = id;

      this.$bus.emit("project-switch", { id: id });
      if (this.$route.path !== "/edit/default") {
        this.$router.push("/edit/default");
      }
    },
    handleCurSimulationChange(id) {},
    handleSimulation() {},
    openAllDiagrams() {
      const allDi = graphHelper.getProjectAllDiagrams(
        app.activeProjectId
      );

      console.log(allDi);
      if (allDi.size === 0) return;
      allDi.forEach((value, key) => {
        this.$bus.emit("diagram-open", { id: key });
        //// treeUtil.openDiagram(value);
      });
    },
    openAddDiagramModal() {
      actions
        .getAction("openCreateDiagramMatrix")
        .onSysMenuClick({ value: "openCreateDiagramMatrix" });
      //// elementMatrix
      ////   .popup({
      ////     x: window.event.clientX,
      ////     y: window.event.clientY,
      ////     title: '选择图表',
      ////     list: treeUtil.getDiagramMenu(),
      ////   })
      ////   .then((item) => {
      ////     treeUtil.createDiagram(item);
      ////   })
      ////   .catch((e) => {
      ////     e && console.error(e);
      ////   });
    },
    //// 项目列表弹框
    remoteProjectList() {
      remoteProjectListModal
        .popup()
        .then((res) => {})
        .catch((err) => {
          err && console.error(err);
        });
      //// onlineProjectApi.fetchRemoteProjects();
      //// onlineProjectApi.createRemoteProject("aaa", "bbb", {model: null});
      //// onlineProjectApi.fetchRemoteProject(app.activeProject.config.id);
      //// versionApi.createVersion(app.activeProject);
    },
    //// 上传新项目
    publishRemoteProject() {
      //// 是否为协同项目
      if (app.activeProject && app.activeProject.config.online) {
        //// 发布弹框
        this.openPublishRemoteProjectModal();
      } else {
        //// 保存弹框
        if (app.activeProject.ui.modified){
          app.$Confirm
            .popup({
              title: '保存',
              content: '保存当前项目',
              subContent: '项目尚未保存，是否需要保存？',
              showCheckbox: false,
              status: 'warn',
              cancelText: '取消',
              okText: '立即保存',
              onClickOk: (vm) => {
                vm.handleCancel();
                this.startSaveProject();
              }
            })
            .then((res) => {
              this.openPublishRemoteProjectModal();
            })
            .catch((e) => {
              e && console.error(e);
            });
        } else {
          this.openPublishRemoteProjectModal();
        }
      }
    },
    startSaveProject(){
      localFile
        .saveProject(app.activeProject)
        .then((res) => {
          this.openPublishRemoteProjectModal();
        });
    },
    //// 弹出发布弹框
    openPublishRemoteProjectModal() {
      publishRemoteProjectModal
        .popup()
        .then((res) => {})
        .catch((err) => {
          err && console.error(err);
        });
    },
    //// 快速更新
    updateLocalProject() {
      //// 判断是否有更新
      let param = {
        projectId: app.activeProject.config.id,
        versionId: app.activeProject.onlineConfig.version || '',
      };
      app.$get(API.PLATFORM_SERVICE_VERSION, param)
        .then((res) => {
          if (res.data) { //// 是最新，无需更新
            app.$messageBox.success({
              text: '当前版本已是最新版本',
              duration: 3000,
            });
          } else { //// 不是最新，需要更新
            updateModel.updateProject();
          }
        })
        .catch((err) => {
          throw err;
        });
    },
    //// 点击提交更改
    pushToRemoteProject() {
      //// 若无更改
      if (!app.activeProject.onlineConfig.needSubmit) {
        this.$messageBox.error({
          text: '没有可提交的更改',
          duration: 10
        });
      } else if (app.activeProject.ui.modified){
        app.$Confirm
          .popup({
            title: "提交",
            subTitle: "当前项目有未保存的更改",
            content: "是否保存？",
            showCheckbox: false,
            status: "warn",
            cancelText: "取消",
            okText: "立即保存",
          })
          .then((res) => {
            localFile.saveProject(app.activeProject)
              .then((resdata) => {
                //// this.openSubmitUpdateModal();
                submitUpdate.openSubmitUpdateModal();
              });
          })
          .catch((e) => {
            e && console.error(e);
          });
      } else {
        submitUpdate.openSubmitUpdateModal();
      }
    },
    //// 更新需求
    updateReq() {
      updateReqModal
        .popup()
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          err && console.error(err);
        });
    },
    devMode(){
      this.isDevMode = !this.isDevMode;
      //// if (this.isDevMode){
      ////   app.eventsMatrix = [[]];
      //// } else {
      ////   app.eventsMatrix = undefined;
      //// }
      
    },
    //// 设置需求同步
    reqSync(){
      setReqSyncModal.popup()
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          err && console.error(err);
        });
    },

    backupSettings() {
      backupSetting.popup();
    },

    logSettings() {
      logSetting.popup();
    },

    restoreBackup() {
      if (!app.activeProject) return;
      restoreBackup.popup({ projectConfig: app.activeProject.config });
    },

    handleWindowClick() {
      this.curShowMenu = "";
    },
    onsc() {
      app.$messageBox.warn({
        text: "暂未提供此功能",
        key: "试用版",
        duration: 10
      });
    },
    print() {
      app.$messageBox.warn({
        text: "暂未提供此功能",
        key: "试用版",
        duration: 10
      });
    },
    search() {
      app.$messageBox.warn({
        text: "暂未提供此功能",
        key: "试用版",
        duration: 10
      });
    },
    showMatlabSetting() {
      if (!this.$globalConfig.isElectron) {
        app.$messageBox.warn({
          text: "在线版不支持此功能",
          key: "不支持",
          duration: 10
        });
        return;
      }
      matlabSetting.popup();
    },
    showDodafSetting(){
      if (!this.$globalConfig.isElectron) {
        app.$messageBox.warn({
          text: "在线版不支持此功能",
          key: "不支持",
          duration: 10
        });
        return;
      }
      dodafSetting.popup();
    },
    handleOpenDodaf(){
      if (!this.$globalConfig.dodafPath){
        this.$messageBox.warn({
          title: '文件缺失',
          text: '请选择dodaf启动文件'

        });
      }

      if (!window.$ele.fs.existsSync(this.$globalConfig.dodafPath)){
        this.$messageBox.warn({
          title: '文件缺失',
          text: 'dodaf启动文件已失效，请重新选择'

        });
      }
      let exec = window.require('child_process').execFile;

      exec(this.$globalConfig.dodafPath, function(err, data) {  
        console.log(err);
        console.log(data.toString());                       
      });  

    },
    handleLogin() {
      if (!this.isAppActive){
        return;
      }
      if (app.$globalConfig.appVersionType !== VersionType.ENTERPRICE){
        app.$Confirm.popup({
          title: '不支持的功能',
          content: '该版本不支持协同功能',
          cancelText: '',
          status: 'warn'
        });
        return;
      }
      loginModal
        .popup()
        .then((res) => {
          //// 获取用户信息
          //// remoteAxios.defaults.headers.Authorization = this.$globalConfig.token;
          this.$get(API.USER_SERVICE_USER_MY_INFO)
            .then((res) => {
              this.$globalConfig.setUser({
                id: res.data.userId,
                userName: res.data.username,
                host: this.$globalConfig.user.host,
                icon: ""
              });
              this.username = res.data.username;
              this.usernameA = res.data.username.substr(0, 1);
              this.projectListDisabled = false;
              this.token = true;
              this.dropdownVisible = false;
            })
            .catch((err) => {});
        })
        .catch((err) => {
          err && console.error(err);
        });
    },
    logout() {
      //// remoteAxios.defaults.baseURL = 'http:////webserver-1.mbse.local:8100';
      //// console.log(remoteAxios.defaults.baseURL);
      this.$get(API.USER_SERVICE_USER_LOGOUT, { loginSource: 'MD_CLIENT' })
        .then((res) => {
          this.token = false;
          this.$globalConfig.clearStorage();
          //// graphNodeStatusFresher.stopTimer();
        })
        .catch((err) => {});
    },
    exportProject(){
      localFile.saveAsProjectMD3(app.activeProject, false);
      //// this.saveAs();

    },
    async exportProjectXML(){
      localFile.saveAsProjectXML(app.activeProject, false);
      //// const jsondata = await this.saveAs();
      //// console.log(jsondata);
    },
    //// 激活
    activeLicense(){
      activeLicenseModal
        .popup()
        .then((res) => {
         
        })
        .catch((err) => {
          err && console.error(err);
        });
    },
    about(){
      aboutModal.popup()
        .then((res) => {
         
        })
        .catch((err) => {
          err && console.error(err);
        });
    },

    //// 打开帮助
    helpqa() {
      localFile.openFile('/files/用户手册-0531.docx');
    }
  },
};
</script>
<style lang="scss" scoped>
.v-header {
	width: 100%;
	.ant-btn {
		padding: 5px;
		border-radius: 0px;
		margin-right: 44px;
		margin-bottom: 0px;
		&:hover {
			box-shadow: 0px 0px 0px 1px rgba(194, 209, 218, 1) inset;
			background: linear-gradient(107deg, #a3dbff 0%, #74c5f8 100%)
		}
		&.ant-dropdown-open {
			background: linear-gradient(107deg, #a3dbff 0%, #74c5f8 100%)
		}
	}
	._window-bar {
		width: 100%;
		background: linear-gradient(90deg, #4390c1 0%, #236fa0 100%);
		-webkit-app-region: drag;
		display: flex;
    position: relative;
    ._text {
      position: absolute;
      color: #fff;
      font-weight: 700;
      left: 92px;
      top: 8px;
    }
		._window-right-btns {
			width: 102px;
			height: 20px;
			margin-right: 8px;
			display: flex;
			._window-btn {
				cursor: pointer;
				text-align: center;
				-webkit-app-region: no-drag;
				&._min-btn {
					width: 28px;
					height: 20px;
					background-image: url("~statics/images/mainpage/iconleftbg1.svg");
					&:hover {
						background-image: url("~statics/images/mainpage/iconleftbg2.svg");
					}
					&:active {
						background-image: url("~statics/images/mainpage/iconleftbg3.svg");
					}
				}
				&._max-btn {
					width: 26px;
					height: 20px;
					background-image: url("~statics/images/mainpage/iconmbg1.svg");
					&:hover {
						background-image: url("~statics/images/mainpage/iconmbg2.svg");
					}
					&:active {
						background-image: url("~statics/images/mainpage/iconmbg3.svg");
					}
				}
				&._close-btn {
					width: 48px;
					height: 20px;
					background-image: url("~statics/images/mainpage/iconrightbg1.svg");
					&:hover {
						background-image: url("~statics/images/mainpage/iconrightbg2.svg");
					}
					&:active {
						background-image: url("~statics/images/mainpage/iconrightbg3.svg");
					}
          background-size: cover;
				}
			}
		}
	}
	._header-content {
		display: flex;
		position: relative;
		//// border-top: 1px solid #b1cee2;
		//// border-left: 1px solid #b1cee2;
		//// border-right: 1px solid #b1cee2;
		background: #e1f4ff;
		._col-left {
			flex: 1;
			height: 63px;
		}
		._col-right {
			width: 41px;
			height: 63px;
			padding-top: 20px;
			padding-right: 0px;
			.__userIcon {
				width: 24px;
				height: 24px;
				line-height: 24px;
				text-align: center;
				color: #fff;
				background-color: #2a76a8;
				border-radius: 50%;
			}
		}
		._system-bar {
			overflow: hidden;
			padding: 0 5px;
			height: 28px;
			._system-btn {
				cursor: pointer;
				padding: 4px;
				color: rgb(32, 32, 32);
				//// font-weight: bold;
				font-size: 14px;
				display: inline-block;
				&:hover {
					box-shadow: inset 0px 0px 0px 1px #c2d1da;
					background: linear-gradient(
						107deg,
						#a3dbff 0%,
						#74c5f8 100%
					);
				}
				&:active {
					box-shadow: inset 0px 0px 0px 1px #c2d1da;
					background: linear-gradient(
						107deg,
						#7fc8f6 0%,
						#3ea5e6 100%
					);
				}
				&._disabled {
					cursor: not-allowed;
					color: rgb(136, 136, 136);
					&:hover {
						box-shadow: none;
						background: inherit;
					}
				}
			}
		}
		._tool-bar {
			padding: 0 5px;
			height: 29px;
			margin-top: 4px;
			position: relative;
			overflow: hidden;
      .avator {
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        color: #fff;
        background-color: #2a76a8;
        border-radius: 50%;
      }
			.topiconline {
				margin-right: 8px;
			}
			._tool-btn {
				display: inline-block;
				height: 28px;
				line-height: 26px;
				border: 1px solid rgba(43, 102, 134, 0);
				cursor: pointer;
				&:hover {
					background: linear-gradient(107deg, #a3dbff 0%, #74c5f8 100%);
					box-shadow: 0px 9px 28px 8px rgba(0, 0, 0, 0.05),
						0px 6px 16px 0px rgba(0, 0, 0, 0.08),
						0px 3px 6px -4px rgba(0, 0, 0, 0.12);
					border: 1px solid #b1cee2;
				}
				&._disabled {
					cursor: not-allowed;
					filter: grayscale(100%);
					&:hover {
						box-shadow: none;
						background: inherit;
						border: 1px solid rgba(0, 0, 0, 0);
					}
				}
				& > img {
					height: 16px;
					margin: 6px 8px;
          margin-top: 5px;
					display: inline-block;
					vertical-align: top;
				}
			}
			.btnfz {
				width: 28px;
				height: 24px;
				margin-top: -10px;
				cursor: pointer;
			}
			._select {
        /deep/ .anticon-down {
          transform: scale(0.8333333);
        }
        /deep/ .ant-select-selection {
          height: 28px;
          line-height: 28px;
          border: 1px solid rgba(43, 102, 134, 0);
          background-color: transparent;
          border-radius: 0;
          transition: unset;
          box-shadow: unset;
          &:hover {
            background: linear-gradient(107deg, #a3dbff 0%, #74c5f8 100%);
					  box-shadow: 0px 9px 28px 8px rgba(0, 0, 0, 0.05),
						0px 6px 16px 0px rgba(0, 0, 0, 0.08),
						0px 3px 6px -4px rgba(0, 0, 0, 0.12);
					  border: 1px solid #b1cee2;
          }
          .ant-select-arrow {
            color: rgba(0, 0, 0, 0.65);
            font-size: 8px;
            margin-top: -5px;
          }
        }
				/deep/ .ant-select-selection__rendered {
					height: 26px;
          margin-left: 4px;
				}
				/deep/ .ant-select-selection__placeholder,
				/deep/ .ant-select-selection-selected-value {
					position: relative;
					top: 0;
					right: unset;
					left: 0;
					max-width: unset;
					height: 26px;
					margin-top: 0;
					overflow: hidden;
					color: rgba(0, 0, 0, 0.65);
					line-height: 26px;
					white-space: nowrap;
					text-align: left;
					text-overflow: ellipsis;
          > img {
            line-height: 16px;
            margin-right: 4px;
          }
          > span {
            line-height: 14px;
          }
				}
        /deep/ .ant-select-selection-selected-value {
          display: flex !important;
          align-items: center;
        }
				&._fz {
					/deep/ .ant-select-selection {
						border-right: 0;
					}
				}
			}
		}
	}
}
</style>
